package com.sys.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * JWT 工具类，用于生成、解析和验证 Token
 */
@Component
public class JwtTokenUtil implements Serializable {

    private static final long serialVersionUID = -2550185165626007488L;

    public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60; // 5 hours

    @Value("${jwt.secret:change-me-default-secret}")
    private String secret;

    // 从 token 中获取用户名
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    // 从 token 中获取过期时间
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    // 获取 token 的所有 claims
    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    // 检查 token 是否过期
    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    // 为用户生成 token
    public String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, username);
    }

    // 创建 token
    private String doGenerateToken(Map<String, Object> claims, String subject) {
        String configured = (secret == null || secret.trim().isEmpty()) ? "change-me-default-secret" : secret;
        byte[] keyBytes = strongKeyBytes(configured);
        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
                .signWith(SignatureAlgorithm.HS512, keyBytes).compact();
    }

    // 生成至少 64 字节的强密钥字节数组（HS512 要求）
    private byte[] strongKeyBytes(String key) {
        byte[] raw = key.getBytes(StandardCharsets.UTF_8);
        if (raw.length >= 64) {
            return raw;
        }
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-512");
            return md.digest(raw);
        } catch (NoSuchAlgorithmException e) {
            // 理论上不会发生，兜底返回重复填充
            byte[] padded = new byte[64];
            for (int i = 0; i < 64; i++) {
                padded[i] = raw[i % raw.length];
            }
            return padded;
        }
    }

    // 验证 token
    public Boolean validateToken(String token, String username) {
        final String usernameFromToken = getUsernameFromToken(token);
        return (usernameFromToken.equals(username) && !isTokenExpired(token));
    }
}